import chalk from 'chalk'

function getErrorRowCol(err: unknown) {
  if (err instanceof Error) {
    if ('row' in err && 'col' in err) {
      return `:${err.row}:${err.col}`
    }
  }
  return ''
}

const warningTime = 50
export async function markTime<T>(
  fn: () => T | Promise<T>,
  logMessage: string,
  logTime = true,
) {
  const start = Date.now()
  try {
    const result = fn()
    const data = result instanceof Promise ? await result : result
    const end = Date.now()
    const diff = end - start
    logTime &&
      console.log(
        diff > warningTime
          ? chalk.yellow(diff + ' ms')
          : chalk.greenBright(diff + ' ms'),
        logMessage,
      )
    return data
  } catch (err) {
    const end = Date.now()
    const diff = end - start
    const args = [
      chalk.red('ERROR'),
      diff > warningTime
        ? chalk.yellow(diff + ' ms')
        : chalk.greenBright(diff + ' ms'),
      logMessage + getErrorRowCol(err),
      '\n',
      err instanceof Error ? err.message : err,
    ]
    console.error(...args)
  }
}
